package com.polaris.live.ui.user

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.UriUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.lxj.xpopup.XPopup
import com.polaris.live.adapter.InfoUserAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.resp.UserResp
import com.polaris.live.common.util.LogExt
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.ActivityInfoUserBinding
import com.polaris.live.interface_bag.S3UploadCallback
import com.polaris.live.popup.AboutPopup
import com.polaris.live.popup.CountryPopup
import com.polaris.live.popup.DataSelectPopup
import com.polaris.live.popup.NikeNamePopup
import com.polaris.live.popup.SelectImagePopup
import com.polaris.live.popup.SetLanguagePopup
import com.polaris.live.resp.bean.InfoUserBean
import com.polaris.live.resp.go_resp.InfoModifyBean
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.CropUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.avatar
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.InfoUserViewModel
import com.polaris.live.widget.avatar.FrameImageUtils
import com.yalantis.ucrop.UCrop
import kotlinx.coroutines.launch

/**
 * InfoUserActivity
 *
 * @author Created by 半仙 on 2023/9/23/023 14:20
 */
class InfoUserActivity : BaseVbActivity<InfoUserViewModel, ActivityInfoUserBinding>() {

    private val mAdapter by lazy { InfoUserAdapter() }

    private var mUserResp: UserResp? = null
    private val mInfoUserList = mutableListOf<InfoUserBean>()

    //本地图片地址
    private var mAvatarUrl: String? = null

    override fun initView(savedInstanceState: Bundle?) {
        initObserver()
        initListener()

        mBinding.recycler.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context)
        }

        mViewModel.getUser()
    }

    private fun initListener() {
        mBinding.bvTitle.setOnRightClientListener {
            UserManager.getUser().userId?.let { it1 ->
                Router.instance.setPath(RoutePath.USER_SPACE_ACTIVITY)
                    .withInt("page", UserConst.From.MY)
                    .withLong("userId", it1).navigation(this)
            }
        }
        mBinding.userAvatar.setOnSingleClickListener {
            mUserResp?.let {
                if (!TextUtils.isEmpty(it.auditingAvatar)) {
                    ToastGravity.showGravity(StringUtils.getString(string.avatar_is_under_review))
                    return@setOnSingleClickListener
                }
            }
            if (mBinding.loadingHead.isVisible) {
                return@setOnSingleClickListener
            }
            XPopup.Builder(this)
                .moveUpToKeyboard(false)
                .isDestroyOnDismiss(true)
                .asCustom(SelectImagePopup(this, onSelectIt = { type ->
                    when (type) {
                        SelectImagePopup.CAMERA -> {
                            CropUtils.startCamera(this, { result ->
                                CropUtils.startCrop(this, result, 5F, 5F, 1080, 1080)
                            }, {})
                        }

                        else -> {
                            CropUtils.startAlbum(this, {
                                updatePhoto(it)
                            }, {}, 5F, 5F, 1080, 1080)
                        }
                    }
                }))
                .show()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            data?.let { result ->
                val file = UriUtils.uri2File(UCrop.getOutput(result))
                file?.let { uploadFile ->
                    updatePhoto(uploadFile.absolutePath)
                }
            }
        } else if (resultCode == RESULT_CANCELED && requestCode == UCrop.REQUEST_CROP) {
            CropUtils.startCamera(this, { result ->
                CropUtils.startCrop(this, result, 5F, 5F, 1080, 1080)
            }, {
            })
        }
    }

    private fun updatePhoto(photoUrl: String) {
        mBinding.loadingHead.visibility = View.VISIBLE
        mAvatarUrl = photoUrl
        lifecycleScope.launch {
            Glide.with(this@InfoUserActivity).load(photoUrl)
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(mBinding.userAvatar)
        }

        ImageUtils.s3Upload(
            photoUrl,
            AppConst.UpLoad.USER_HEAD,
            callback = object : S3UploadCallback {
                override fun onSuccess(url: String, size: Pair<Int, Int>?) {
                    mViewModel.infoUpData(InfoModifyBean(avatar = url))
                }

                override fun onFailure(t: Throwable) {
                    LogExt.logE("--net", t)
                    showOnResume()
                }
            })
    }

    private fun initObserver() {
        mViewModel.mUserLiveData.observe(this) {
            initData(it)
        }
        mViewModel.mInfoUpLiveData.observe(this) { resultState ->
            mBinding.loadingHead.visibility = View.GONE
            parseState(resultState, {
                mViewModel.getUser()
            }, {
                showOnResume()
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private fun showOnResume() {
        if (mUserResp?.avatarModified != 0) {
            Glide.with(this@InfoUserActivity).load(ImageUtils.imgPathMiddle(mUserResp?.avatar))
                .avatar().into(mBinding.userAvatar)
        }
    }

    private fun initData(user: UserResp) {
        mUserResp = user
        mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(mUserResp?.decoration?.avatarFrame))
        if (user.avatarModified != 0 && mAvatarUrl == null) {
            Glide.with(this@InfoUserActivity).load(ImageUtils.imgPathMiddle(user.avatar))
                .avatar().into(mBinding.userAvatar)
        }
        mInfoUserList.clear()
        mInfoUserList.add(
            InfoUserBean(
                perfect = PERFECT,
                type = NOINFO,
                key = getString(string.info_user_uid),
                value = user.userNumber.toString()
            )
        )
        mInfoUserList.add(
            InfoUserBean(
                perfect = if (user.nicknameModified == 1) PERFECT else NOPERFECT,
                type = INFO,
                key = getString(string.info_user_name),
                value = user.nickname
            )
        )
        mInfoUserList.add(
            InfoUserBean(
                perfect = if (user.birthdayModified == 1) PERFECT else NOPERFECT,
                type = INFO,
                key = getString(string.birthday),
                value = user.birthday?.toString()
            )
        )
        mInfoUserList.add(
            InfoUserBean(
                perfect = PERFECT,
                type = NOINFO,
                key = getString(string.info_user_gender),
                value = user.sex.toString()
            )
        )
        mInfoUserList.add(
            InfoUserBean(
                perfect = PERFECT,
                type = NOINFO,
                key = getString(string.first_language),
                value = user.profile?.language
            )
        )
        mInfoUserList.add(
            InfoUserBean(
                perfect = PERFECT,
                type = INFO,
                key = getString(string.info_user_second_language),
                value = user.profile?.secondLanguage?.let { CommonUtils.getLanguageNameFromLocaleCode(it) }
            )
        )
        if (user.profile?.modifyAboutMe == true) {
            mInfoUserList.add(
                InfoUserBean(
                    perfect = PERFECT,
                    type = INFO,
                    key = getString(string.info_user_about_me),
                    keyDown = if (user.profile?.aboutMe.isNullOrEmpty()) getString(string.provide_description) else user.profile?.aboutMe
                )
            )
        }
        val value = if (user.profile?.secondCountryHidden == 1L) {
            StringUtils.getString(string.Hidden)
        } else {
            user.profile?.secondCountry ?: ""
        }
        mInfoUserList.add(
            InfoUserBean(
                perfect = if (user.countryModified == 1) PERFECT else NOPERFECT,
                type = INFO,
                key = getString(string.info_user_country),
                value = value
            )
        )
        if (user.coverPhoto?.validCover == true) {
            mInfoUserList.add(
                InfoUserBean(
                    perfect = PERFECT,
                    type = INFO,
                    key = getString(string.photo),
                    keyDown = getString(string.upload_your_album)
                )
            )
        }

        mAdapter.setList(mInfoUserList)

        mAdapter.setOnItemClickListener { _, _, position ->
            when (mAdapter.data[position].key) {
                getString(string.info_user_name) -> {
                    XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .asCustom(
                            NikeNamePopup(
                                this,
                                mViewModel,
                                user.nickname ?: "",
                                mOnNikeNameCallBack = {
                                    mViewModel.getUser()
                                })
                        )
                        .show()
                }

                getString(string.info_user_birthday) -> {
                    XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .asCustom(
                            DataSelectPopup(
                                this,
                                mOnSelectCallBack = { year, month, day ->
                                    mViewModel.infoUpData(InfoModifyBean(birthday = "${year}-${month}-${day}"))
                                }, user.birthday
                            )
                        )
                        .show()
                }

                getString(string.info_user_second_language) -> {
                    XPopup.Builder(this)
                        .moveUpToKeyboard(false)
                        .isDestroyOnDismiss(true)
                        .asCustom(SetLanguagePopup(this, mOnSelectLanguage = {
                            mViewModel.getUser()
                        }, mViewModel))
                        .show()
                }

                getString(string.info_user_about_me) -> {
                    if (user.profile?.auditingAboutMe == true) {
                        ToastGravity.showGravity(StringUtils.getString(string.under_review))
                        return@setOnItemClickListener
                    }
                    XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .asCustom(
                            AboutPopup(
                                this,
                                user.profile?.aboutMe ?: "",
                                mOnAboutCallBack = { about ->
                                    mViewModel.infoUpData(InfoModifyBean(aboutMe = about))
                                })
                        )
                        .show()
                }

                getString(string.info_user_country) -> {
                    XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .asCustom(
                            CountryPopup(
                                this,
                                mViewModel,
                                if (UserManager.getUser().profile?.secondCountryHidden == 1L) {
                                    null
                                } else {
                                    UserManager.getUser().profile?.secondCountry
                                } ?: ""
                            ) { countryCode, isHidden ->
                                if (isHidden) {
                                    mViewModel.infoUpData(InfoModifyBean(secondCountryHidden = 1))
                                } else {
                                    mViewModel.infoUpData(InfoModifyBean(secondCountry = countryCode))
                                }
                            }
                        )
                        .show()
                }

                getString(string.photo) -> {
                    Router.builder(RoutePath.USER_SPACE_ACTIVITY)
                        .withInt("page", UserConst.From.MY)
                        .withLong("userId", UserManager.getUserId())
                        .navigation(this)
                }
            }
        }
    }

    companion object {

        const val PERFECT = 1       //完善
        const val NOPERFECT = 2     //待完善
        const val INFO = 1          //可编辑
        const val NOINFO = 2        //不可编辑
    }
}